<template>
  <div>

    <!-- 添加导演表单 -->
    <el-form
      :model="form"
      label-width="80px"
      style="width: 500px"
      :rules="rules"
      ref="form"
    >
      <el-form-item label="导演姓名" prop="directorName">
        <el-input v-model="form.directorName"></el-input>
      </el-form-item>
      <el-form-item label="选择头像" prop="directorAvatar">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:9000/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.directorAvatar" :src="form.directorAvatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">立即新增</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import myaxios from "@/http/MyAxios";
import httpApi from "@/http/index";
export default {
  data() {
    return {
      form: {
        directorName: "",
        directorAvatar: "",
      },
      rules: {
        directorName: [
          { required: true, message: "导演姓名不能为空", trigger: "blur" },
        ],
        directorAvatar: [
          { required: true, message: "导演头像不能为空", trigger: "blur" },
        ],
      },
    };
  },

  methods: {
    // 将云存储返回的图片地址赋值
    handleAvatarSuccess(res, file) {
      this.form.directorAvatar = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          httpApi.directorApi.addDirector(this.form).then(res=>{
            if (res.data.code === 200) {
              this.$message.success("添加成功");
            } else {
              this.$message.error("添加失败");
            }
          })
          // let url = "http://localhost:3010/movie-actor/add";
          // myaxios.post(url, this.form).then((res) => {
          //   console.log(res);
          // });
          // 重置表单
          this.$refs["form"].resetFields();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  display: block;
}
</style>